Ext.namespace('Ext.ux');

Ext.ux.ObjectReader = function(meta, recordType){
    meta = meta || {};
    Ext.ux.ObjectReader.superclass.constructor.call(this, meta, recordType || meta.fields);
};
Ext.extend(Ext.ux.ObjectReader, Ext.data.DataReader, {
    read : function(response){
        var o = response;
        if(!o) {
            throw {message: "ObjectReader.read: object not found"};
        }
        if(o.metaData){
            delete this.ef;
            this.meta = o.metaData;
            this.recordType = Ext.data.Record.create(o.metaData.fields);
            this.onMetaChange(this.meta, this.recordType, o);
        }
        return this.readRecords(o);
    },

    // private function a store will implement
    onMetaChange : function(meta, recordType, o){

    },

    simpleAccess: function(obj, subsc) {
    	return obj[subsc];
    },

	clone : function(o) {
		// nothing with null
		if(o == null) return o;
	
		var n = null;				
		// depends on type
		var t = typeof(o);
		if(o instanceof Array) {
			n = new Array();
			for (var i=0; i<o.length; i++)
				n[i] = this.clone(o[i]);
		} else if (o instanceof Object) {
			var n = new Object();
			for(var i in o) {
				n[i] = this.clone(o[i]);
			}
		} else {
			n = o;
		}
		return n;
	},
	
    readRecords : function(o){
		o = this.clone(o);
        this.objectData = o;
        var s = this.meta, Record = this.recordType,
            f = Record.prototype.fields, fi = f.items, fl = f.length;

		var getId = function(){return(null)};
		if (this.meta.id) {
			var idField = this.meta.id;
			getId = function(r) {
				return(rec[idField]);
			}
		}

        var records = [];
	    for(var i = 0; i < o.length; i++){
	        var record = new Record(o[i], getId(o[i]));
	        records[i] = record;
	    }
	    return {
	        success : true,
	        records : records,
	        totalRecords : records.length
	    };
    },

	// write - input objects, write out cloned objects    
	write : function(records) {
		// clone so we do not confuse objects
		return(this.clone(records));
	}
});

